package ferp.android.social;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.*;
import android.widget.LinearLayout;
import ferp.core.log.Log;

/**
 * User: igorgok
 * Date: 10/2/13 9:32 AM
 *
 * FB "Like" button code is generated for iframe. HTML5 version does not work as file:// and https://
 * do not get along
 */
public class LikesManager
{
  public static final String PAGE = "file:///android_asset/like.html";

  public static interface Listener
  {
    void onFacebookLikeSet();
    void onFacebookLikeRemoved();
    void onGooglePlusOneSet();
    void onGooglePlusOneRemoved();
  }

  public static void initialize(Activity activity, int wvid, Listener listener)
  {
    WebView webview = (WebView)activity.findViewById(wvid);

    if (webview != null)
    {
      Display display = activity.getWindowManager().getDefaultDisplay();

      initialize(webview, listener, Math.min(display.getWidth(), display.getHeight()));
    }
  }

  // instance of this class is passed to the webview which then calls its methods
  private static final class Callbacks
  {
    Callbacks(Listener listener)
    {
      this.listener = listener;
    }

    // JS callback
    public void onGooglePlusOneClicked(String url, String state)
    {
      //Log.debug(Log.TAG, "+1 for " + url + " is " + state);

      if (state.contentEquals("on"))
        listener.onGooglePlusOneSet();
      else
        listener.onGooglePlusOneRemoved();
    }

    final Listener listener;
  }

  private static void initialize(final WebView webview, final Listener listener, int dimension)
  {
    WebSettings s = webview.getSettings();
    int scale = Math.min(400, 80 * dimension / 240);

    Log.debug(Log.TAG, "initializing webview for screen minimal dimension " + dimension + ", scale " + scale);

    box.width  = Math.round(91 * scale / 100);
    box.height = Math.round(57 * scale / 100);

    s.setDefaultTextEncodingName("UTF-8");
    s.setJavaScriptEnabled(true);
    s.setJavaScriptCanOpenWindowsAutomatically(true);
    s.setBuiltInZoomControls(false);
    s.setSupportZoom(false);
    //s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    s.setUseWideViewPort(false);

    // CookieManager.getInstance().removeAllCookie(); // debug only
    CookieManager.getInstance().setAcceptCookie(true);

    webview.setInitialScale(scale);
    webview.setBackgroundColor(Color.TRANSPARENT);
    webview.addJavascriptInterface(new Callbacks(listener), "callbacks");
    webview.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
    webview.setWebViewClient(new WebViewClient()
    {
      @Override
      public void onLoadResource(WebView view, String url)
      {
        super.onLoadResource(view, url);

        //Log.log.debug(Log.TAG, "loading resource from: " + url);

        // check URL string to determine if there was FB like/unlike
        if (url.contains("like/connect"))
          listener.onFacebookLikeSet();
        else
          if (url.contains("like/disconnect"))
            listener.onFacebookLikeRemoved();
      }

      @Override
      public void onPageStarted(WebView view, String url, Bitmap favicon)
      {
        Log.debug(Log.TAG, "URL started: " + url);

        if (url.contains("like.html"))
          view.setLayoutParams(box);

        super.onPageStarted(view, url, favicon);
      }

      @Override
      public void onPageFinished(WebView view, String url)
      {
        Log.debug(Log.TAG, "URL finished: " + url);

        super.onPageFinished(view, url);

        // facebook related workaround over blank page after authorization finished
        if (url.contains("close_popup"))
        {
          Uri uri = Uri.parse(url);
          String like = uri.getQueryParameter("reload");

          Log.debug(Log.TAG, "close popup workaround: " + like);

          view.loadUrl(like == null || like.length() == 0 ? PAGE : like);
        }
        else
          if (url.contains("like.php") || url.contains("widget_poster"))
          {
            // the following should reload the view and restore start restoring its dimensions
            //view.setLayoutParams(new LinearLayout.LayoutParams(82, 86));
            view.loadUrl(PAGE);
          }
          else
            if (!url.contains("like.html") && view.getLayoutParams() != wrap)
              view.setLayoutParams(wrap);

        CookieSyncManager.getInstance().sync();
      }

      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url)
      {
        return false;
      }

      @Override
      public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
      {
        // in case of an error we hide the web view
        view.setVisibility(View.INVISIBLE);
      }
    });

    webview.loadUrl(PAGE);
  }

  private static final LinearLayout.LayoutParams wrap = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
  private static final LinearLayout.LayoutParams box = new LinearLayout.LayoutParams(91, 57);
}
